<template>
  <div class="space-list">
    <!-- 网格视图 -->
    <div v-if="viewMode === 'grid'" class="grid-view">
      <div 
        v-for="space in spaces" 
        :key="space.id" 
        class="space-card"
        @click="$emit('enter-space', space)"
      >
        <div class="card-header">
          <div class="space-avatar" :style="{ backgroundColor: space.color || '#409EFF' }">
            {{ space.name ? space.name.charAt(0) : 'S' }}
          </div>
          <div class="card-actions">
            <el-dropdown trigger="click" @click.stop>
              <el-icon class="action-icon"><MoreFilled /></el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="$emit('enter-space', space)">
                    <el-icon><View /></el-icon>
                    进入空间
                  </el-dropdown-item>
                  <el-dropdown-item @click="$emit('edit-space', space)">
                    <el-icon><Edit /></el-icon>
                    编辑空间
                  </el-dropdown-item>
                  <el-dropdown-item @click="duplicateSpace(space)">
                    <el-icon><CopyDocument /></el-icon>
                    复制空间
                  </el-dropdown-item>
                  <el-dropdown-item @click="exportSpace(space)">
                    <el-icon><Download /></el-icon>
                    导出空间
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="$emit('delete-space', space.id)">
                    <el-icon><Delete /></el-icon>
                    删除空间
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <div class="card-content">
          <h3 class="space-title">{{ space.name }}</h3>
          <p class="space-description">{{ space.description || '暂无描述' }}</p>
          
          <div class="space-stats">
            <div class="stat-item">
              <el-icon><Document /></el-icon>
              <span>{{ space.pageCount || 0 }} 页面</span>
            </div>
            <div class="stat-item">
              <el-icon><View /></el-icon>
              <span>{{ space.viewCount || 0 }} 阅读</span>
            </div>
          </div>
          
          <div class="space-meta">
            <div class="meta-left">
              <el-tag 
                :type="getVisibilityTagType(space.visibility)" 
                size="small"
              >
                {{ getVisibilityText(space.visibility) }}
              </el-tag>
              <el-tag 
                :type="getScopeTagType(space.scopeType)" 
                size="small"
              >
                {{ getScopeText(space.scopeType) }}
              </el-tag>
            </div>
            <div class="meta-right">
              <span class="update-time">{{ formatRelativeTime(space.updatedAt) }}</span>
            </div>
          </div>
        </div>
        
        <div class="card-footer">
          <div class="creator-info">
            <el-avatar :size="20" class="creator-avatar">
              {{ space.createdBy?.username?.charAt(0) || 'U' }}
            </el-avatar>
            <span class="creator-name">{{ space.createdBy?.username || '未知用户' }}</span>
          </div>
          <div class="favorite-action">
            <el-icon 
              class="favorite-icon" 
              :class="{ 'is-favorite': space.isFavorite }"
              @click.stop="toggleFavorite(space)"
            >
              <Star />
            </el-icon>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 列表视图 -->
    <div v-if="viewMode === 'list'" class="list-view">
      <el-table :data="spaces" style="width: 100%" @row-click="handleRowClick">
        <el-table-column width="60">
          <template #default="{ row }">
            <div class="table-avatar" :style="{ backgroundColor: row.color || '#409EFF' }">
              {{ row.name ? row.name.charAt(0) : 'S' }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="空间名称" min-width="200">
          <template #default="{ row }">
            <div class="space-name-cell">
              <span class="space-name">{{ row.name }}</span>
              <div class="space-tags">
                <el-tag 
                  :type="getVisibilityTagType(row.visibility)" 
                  size="small"
                >
                  {{ getVisibilityText(row.visibility) }}
                </el-tag>
                <el-tag 
                  :type="getScopeTagType(row.scopeType)" 
                  size="small"
                >
                  {{ getScopeText(row.scopeType) }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" min-width="200">
          <template #default="{ row }">
            <span class="description-text">{{ row.description || '暂无描述' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="统计" width="120">
          <template #default="{ row }">
            <div class="stats-cell">
              <div class="stat-row">
                <el-icon><Document /></el-icon>
                <span>{{ row.pageCount || 0 }}</span>
              </div>
              <div class="stat-row">
                <el-icon><View /></el-icon>
                <span>{{ row.viewCount || 0 }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="创建者" width="120">
          <template #default="{ row }">
            <div class="creator-cell">
              <el-avatar :size="24" class="creator-avatar">
                {{ row.createdBy?.username?.charAt(0) || 'U' }}
              </el-avatar>
              <span class="creator-name">{{ row.createdBy?.username || '未知用户' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="更新时间" width="120">
          <template #default="{ row }">
            <span class="update-time">{{ formatRelativeTime(row.updatedAt) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <div class="table-actions">
              <el-icon 
                class="favorite-icon" 
                :class="{ 'is-favorite': row.isFavorite }"
                @click.stop="toggleFavorite(row)"
              >
                <Star />
              </el-icon>
              <el-dropdown trigger="click" @click.stop>
                <el-icon class="action-icon"><MoreFilled /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="$emit('enter-space', row)">
                      <el-icon><View /></el-icon>
                      进入空间
                    </el-dropdown-item>
                    <el-dropdown-item @click="$emit('edit-space', row)">
                      <el-icon><Edit /></el-icon>
                      编辑空间
                    </el-dropdown-item>
                    <el-dropdown-item @click="duplicateSpace(row)">
                      <el-icon><CopyDocument /></el-icon>
                      复制空间
                    </el-dropdown-item>
                    <el-dropdown-item @click="exportSpace(row)">
                      <el-icon><Download /></el-icon>
                      导出空间
                    </el-dropdown-item>
                    <el-dropdown-item divided @click="$emit('delete-space', row.id)">
                      <el-icon><Delete /></el-icon>
                      删除空间
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import {
  MoreFilled, View, Edit, CopyDocument, Download, Delete,
  Document, Star
} from '@element-plus/icons-vue'
import request from '@/utils/request'

// Props
const props = defineProps({
  spaces: {
    type: Array,
    default: () => []
  },
  viewMode: {
    type: String,
    default: 'grid',
    validator: (value) => ['grid', 'list'].includes(value)
  }
})

// Emits
const emit = defineEmits(['enter-space', 'edit-space', 'delete-space'])

// 方法
const getVisibilityText = (visibility) => {
  const map = {
    'private': '私有',
    'public': '公开'
  }
  return map[visibility] || '未知'
}

const getVisibilityTagType = (visibility) => {
  const map = {
    'private': 'warning',
    'public': 'success'
  }
  return map[visibility] || ''
}

const getScopeText = (scopeType) => {
  const map = {
    'user': '个人',
    'user_group': '团队'
  }
  return map[scopeType] || '未知'
}

const getScopeTagType = (scopeType) => {
  const map = {
    'user': 'info',
    'user_group': 'primary'
  }
  return map[scopeType] || ''
}

const formatRelativeTime = (timestamp) => {
  if (!timestamp) return '未知'
  
  const now = Date.now()
  const time = new Date(timestamp).getTime()
  const diff = now - time
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  const month = 30 * day
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`
  } else {
    return new Date(timestamp).toLocaleDateString('zh-CN')
  }
}

const handleRowClick = (row) => {
  emit('enter-space', row)
}

const toggleFavorite = async (space) => {
  try {
    const response = await request.post(`/api/spaces/${space.id}/favorite`, {
      isFavorite: !space.isFavorite
    })
    
    if (response.data.code === '200') {
      space.isFavorite = !space.isFavorite
      ElMessage.success(space.isFavorite ? '已添加到收藏' : '已取消收藏')
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error) {
    console.error('切换收藏状态失败:', error)
    ElMessage.error('操作失败')
  }
}

const duplicateSpace = async (space) => {
  try {
    const response = await request.post(`/api/spaces/${space.id}/duplicate`)
    if (response.data.code === '200') {
      ElMessage.success('复制成功')
      // 触发父组件刷新列表
      emit('refresh')
    } else {
      ElMessage.error(response.data.msg || '复制失败')
    }
  } catch (error) {
    console.error('复制空间失败:', error)
    ElMessage.error('复制失败')
  }
}

const exportSpace = (space) => {
  ElMessage.info('导出功能开发中')
}
</script>

<style scoped>
.space-list {
  width: 100%;
}

/* 网格视图样式 */
.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.space-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.space-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  border-color: #409EFF;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.space-avatar {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  font-weight: bold;
  flex-shrink: 0;
}

.card-actions {
  opacity: 0;
  transition: opacity 0.2s;
}

.space-card:hover .card-actions {
  opacity: 1;
}

.action-icon {
  color: #666;
  cursor: pointer;
  padding: 6px;
  border-radius: 6px;
  transition: all 0.2s;
}

.action-icon:hover {
  background-color: #f5f5f5;
  color: #409EFF;
}

.card-content {
  margin-bottom: 16px;
}

.space-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.space-description {
  margin: 0 0 16px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  min-height: 42px;
}

.space-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 13px;
}

.stat-item .el-icon {
  font-size: 14px;
}

.space-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.meta-left {
  display: flex;
  gap: 8px;
}

.meta-right {
  flex-shrink: 0;
}

.update-time {
  color: #999;
  font-size: 12px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.creator-avatar {
  background-color: #f0f0f0;
  color: #666;
  font-size: 12px;
}

.creator-name {
  color: #666;
  font-size: 13px;
}

.favorite-action {
  display: flex;
  align-items: center;
}

.favorite-icon {
  color: #ccc;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 16px;
}

.favorite-icon:hover {
  color: #ffd700;
}

.favorite-icon.is-favorite {
  color: #ffd700;
}

/* 列表视图样式 */
.list-view {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.table-avatar {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
  font-weight: bold;
}

.space-name-cell {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.space-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.space-tags {
  display: flex;
  gap: 6px;
}

.description-text {
  color: #666;
  font-size: 13px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.stats-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-row {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 12px;
}

.stat-row .el-icon {
  font-size: 12px;
}

.creator-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .grid-view {
    grid-template-columns: 1fr;
  }
  
  .space-card {
    padding: 16px;
  }
  
  .space-stats {
    gap: 12px;
  }
  
  .meta-left {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .space-card {
    padding: 12px;
  }
  
  .space-title {
    font-size: 16px;
  }
  
  .card-footer {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f8f9fa !important;
}

:deep(.el-table__row) {
  cursor: pointer;
}

/* 表格单元格内边距调整 */
:deep(.el-table .cell) {
  padding: 8px 12px;
}
</style>